package com.modnique;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.HasParentFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.dao.DBUtil;
import com.dao.DealBean;
import com.util.CategoryMapping;

public class ModNiqueHtmlParser {
	
	public  void parserModNique(String url) throws Exception{
		
		DealBean modniqueBean = new DealBean();
		
		modniqueBean.setBuy_url(url);
		
		String modelId = "";
        
		modniqueBean.setModel_id(modelId);
		
		String endsTime = "";
        
		modniqueBean.setEnds_time(endsTime);
        
        String souceSite = "ModNique";
        
        modniqueBean.setSouce_site(souceSite);
		
		Parser parser;
		
		String skuId = "";
		
		try {
			
			parser = new Parser(url);
			
			parser.setEncoding("UTF-8");
			
            NodeFilter skuIdNodeFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class", "mts rfloat contrast"));
            
            NodeList skuIdNodeList = parser.extractAllNodesThatMatch(skuIdNodeFilter); 
            
            if (skuIdNodeList != null && skuIdNodeList.size() > 0) {  

                Node skuIdNode = skuIdNodeList.elementAt(0);  

                String[] skuIdList = skuIdNode.toPlainTextString().split(":"); 
                
                skuId = skuIdList[1].trim();

                modniqueBean.setSku_id(skuId);

            }
            
            parser.reset();
            
            NodeFilter imageUrlFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("id", "product_imagelist"));

            NodeList imageUrlList = parser.extractAllNodesThatMatch(imageUrlFilter);
            
            if (imageUrlList != null && imageUrlList.size() > 0) { 
            	
            	Parser imageparser = new Parser(imageUrlList.toHtml());
            	
            	NodeFilter imageUrlNodeFilter = new TagNameFilter("a");
            	
            	NodeList imageUrlNodeList = imageparser.extractAllNodesThatMatch(imageUrlNodeFilter);
            	
            	if (imageUrlList != null && imageUrlList.size() > 0) { 

                Tag imageUrlNode = (Tag)imageUrlNodeList.elementAt(0);
                
                String imageUrl = imageUrlNode.getAttribute("href");
                
                modniqueBean.setImage_url(imageUrl); 

                saveFile(imageUrl, skuId);
            }
            }
            
            parser.reset();
            
            NodeFilter productNameNodeFilter = new TagNameFilter("h1");
            
            NodeList productNameNodeList = parser.extractAllNodesThatMatch(productNameNodeFilter);
             
              if (productNameNodeList != null && productNameNodeList.size() > 0) {  

                  Node productNameNode = productNameNodeList.elementAt(0);  

                  String productName = productNameNode.toPlainTextString().trim();  

                  modniqueBean.setProduct_name(productName); 

              } 
              
            parser.reset();
            
            NodeFilter salePriceNodeFilter = new AndFilter(new TagNameFilter("span"),new HasAttributeFilter("class", "price lfloat"));
            
            NodeList salePriceNodeList = parser.extractAllNodesThatMatch(salePriceNodeFilter);
             
              if (salePriceNodeList != null && salePriceNodeList.size() > 0) {  

                  Node salePriceNode = salePriceNodeList.elementAt(0);  

                  String salePrice = salePriceNode.toPlainTextString().trim();
                  
                  modniqueBean.setSale_price(salePrice);
                  
                  }
              
            parser.reset();
            
            NodeFilter originalPriceNodeFilter = new AndFilter(new TagNameFilter("span"),new HasAttributeFilter("class", "bare mrs"));
            
            NodeList originalPriceNodeList = parser.extractAllNodesThatMatch(originalPriceNodeFilter);
             
              if (originalPriceNodeList != null && originalPriceNodeList.size() > 0) {  

                  Node originalPriceNode = originalPriceNodeList.elementAt(0);  

                  String originalPrice = originalPriceNode.toPlainTextString().trim();

                  modniqueBean.setOriginal_price(originalPrice);
                  
              } 
           
              parser.reset();
              
              NodeFilter brandFilter = new AndFilter(new TagNameFilter("a"),new HasAttributeFilter("id", "productBackToEventsLinkBrand"));
              
              NodeList brandList = parser.extractAllNodesThatMatch(brandFilter);
              
              if (brandList != null && brandList.size() > 0) {
              
              	Node brandNode = brandList.elementAt(0);
              	
              	String brand = brandNode.toPlainTextString().trim();
              	
              	modniqueBean.setBrand(brand);
              
              }
              
              parser.reset();
              
              NodeFilter categoryFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("id", "tab1"));
	            
	            NodeList categoryList = parser.extractAllNodesThatMatch(categoryFilter);
	             
	              if (categoryList != null && categoryList.size() > 0) { 
	            	  
	            	  Parser categoryNodeParser = new Parser(categoryList.toHtml());
	            	  
	            	  NodeFilter categoryNodeFilter = new TagNameFilter("p");
	            	  
	            	  NodeList categoryNodeList = categoryNodeParser.extractAllNodesThatMatch(categoryNodeFilter);

                     if(categoryNodeList != null && categoryNodeList.size() > 0){
                    	 
                  	   for(Node categoryNode : categoryNodeList.toNodeArray()){
                  		   
                  		   String categoryNodeContent = categoryNode.toPlainTextString().trim();
                  		   
                  		   if (categoryNodeContent.contains("Gender:")){
                  			   
                  			   String[] list = categoryNodeContent.split(":");
                  			   
                  			   String category = CategoryMapping.getType1(list[1]);
                  			   
                  			 modniqueBean.setCategory1(category);
                  			   
                                  }
                  	   }
                     }

	              } 
	              
	              parser.reset();
	              
	              NodeFilter itemFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("id", "tab1"));
		            
		            NodeList itemList = parser.extractAllNodesThatMatch(itemFilter);
		             
		              if (itemList != null && itemList.size() > 0) { 
		            	  
		            	  Parser itemNodeParser = new Parser(itemList.toHtml());
		            	  
		            	  NodeFilter itemNodeFilter = new TagNameFilter("p");
		            	  
		            	  NodeList itemNodeList = itemNodeParser.extractAllNodesThatMatch(itemNodeFilter);

	                     if(itemNodeList != null && itemNodeList.size() > 0){
	                    	 
	                  	   for(Node itemNode : itemNodeList.toNodeArray()){
	                  		   
	                  		   String itemNodeContent = itemNode.toPlainTextString().trim();
	                  		   
	                  		   if (itemNodeContent.contains("Item Type:")){
	                  			   
	                  			   String[] list = itemNodeContent.split(":");
	                  			   
	                  			   String item = CategoryMapping.getType2(list[1]);
	                  			   
	                  			   modniqueBean.setCategory2(item);
	                  			   
	                                  }
	                  	   }
	                     }

		              }
              
	              parser.reset();
	              
	              NodeFilter productDescriptionFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("id", "tab1"));
		            
		            NodeList productDescriptionList = parser.extractAllNodesThatMatch(productDescriptionFilter);
		             
		              if (productDescriptionList != null && productDescriptionList.size() > 0) { 
		            	
		            	    Node productDescriptionNode = productDescriptionList.elementAt(0);
		                	
		                	String productDescription = productDescriptionNode.toPlainTextString().trim();
		                	
		                	modniqueBean.setProduct_description(productDescription);

		              } 
			 
		} catch (ParserException e) {
			
			e.printStackTrace();
		}  
        
		 DBUtil db = new DBUtil();
         
         if(modniqueBean.getSku_id()!=null){
         
         db.save(modniqueBean);
         
         }
		
	}
	
	 private static void saveFile(String imgString, String productId) throws Exception {
		  	URL url;
		  	File outFile;
		  	OutputStream os = null;
		  	InputStream is = null;
				try {
					url = new URL(imgString);
					outFile = new File("C:/nordstrom/img/"+productId+".jpg");
					os = new FileOutputStream(outFile);
					is = url.openStream();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				byte[] buff = new byte[1024];
				while(true) {
					int readed = is.read(buff);
					if(readed == -1) {
						break;
					}
					byte[] temp = new byte[readed];
					System.arraycopy(buff, 0, temp, 0, readed);
					os.write(temp);
				}
				is.close(); 
		      os.close();
			}

}
